package net.jingkao.app.common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件工具
 * @author chao
 *
 */
public class FileUtils {
	
	private static Logger log = Logger.getLog(FileUtils.class);
	
	public static void writeToFile(File file, byte[] data){
		FileOutputStream out = null;
		try{
			out = new FileOutputStream(file);
			out.write(data);
		}catch(Exception e){
			log.e(e);
		}finally{
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}
		
	}

	public static byte[] readFromFile(File cacheFile) {
		if(!cacheFile.exists()){
			return null;
		}
		byte[] data = new byte[1024];
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		FileInputStream in = null;
		try{
			in = new FileInputStream(cacheFile);
			int len = 0;
			while((len = in.read(data)) > 0){
				out.write(data, 0 , len);
			}
		}catch(Exception e){
			log.e(e);
		}finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
				}
			}
			try {
				out.close();
			} catch (IOException e) {
			}
		}
		return out.toByteArray();
	}

}
